

var idCount = 0;
var rowCount = 0;
var columns = new Array();
var rows = new Array();
var saved = false;
var mainComponents = new Array();
var mainUsers = new Array();


function setPickUsersPosition(){
	var ctUser = getById("pickUsersCt");
	ctUser.style.top = "214px";
	ctUser.style.left = "238px";
}

function showPickUsers(){
	var ctUser = getById("pickUsersCt");
	setPickUsersPosition();
	ctUser.style.display = "inline";
	
}

function applyUsers(){
	var value = "";
	var usr = new Array();
	
	for ( var i = 0; i < mainUsers.length; i++) {
		var cmpCb = mainUsers[i];

		if(cmpCb.getValue() == true){
			usr.push(cmpCb.getDescription());
		}
	}
	
	var cont = 0;
	for ( var i = 0; i < usr.length; i++) {
		value += usr[i];
		if(cont < (usr.length - 1)){
			value += ", ";
		}
		cont++;
	}
	
	compreviser.setValue(value);
	var ctUser = getById("pickUsersCt");
	ctUser.style.display = "none";
}

function createPickUsers(users){
	var usersMainCt = getById("pickUsersCt");
	var usersCt = getById("pickUsersFields");
	
	var table = createEl("table");
	usersCt.appendChild(table);
	
	var ctHeight = 30;
	for ( var i = 0; i < users.length; i++) {
		
		ctHeight += 25;
		var row = createEl("tr");
		table.appendChild(row);
				
		var tdCheck = createEl("td");
		tdCheck.id = "$"+users[i];
		
		row.appendChild(tdCheck);
		var check = new CheckBox(users[i],tdCheck.id);
		
		check.setDescription(users[i]);
		
		var tdDescr = createEl("td");
		row.appendChild(tdDescr);
		tdDescr.innerHTML = users[i];		
		
		mainUsers.push(check);
	}
	
	usersMainCt.style.height = ctHeight + "px";
	
	for ( var i = 0; i < mainUsers.length; i++) {
		var cbCmp = mainUsers[i];
		cbCmp.render();
	}
}

function internalGoBack(){
	if(saved == false){
		var ret = confirm("Há dados não salvos, quer sair mesmo assim?");
		if(ret  == true){
			goBack();
		}
	}else{
		goBack();
	}
}	

function validate(){
	var message = "Os seguintes erros foram encontrados: \n";
	
	//valida os componentes principais do checklist
	var hasInvalidMainFields = false;
	var invalidMainFields = new Array();
	for ( var i = 0; i < mainComponents.length; i++) {
		var field  = mainComponents[i];
		if(field.getValue() == ""){
			field.htmlElement.onchange = new Function("changeInvalidComponent(\""+field.getId()+"\",\"mainComponents\");");
			field.setInvalid(true);
			hasInvalidMainFields = true;
			invalidMainFields.push(field);
		}
	}
	
	if(hasInvalidMainFields == true){
		message += " - Informe os seguintes dados da lista: \n";
		for ( var i = 0; i < invalidMainFields.length; i++) {
			message += "		- "+invalidMainFields[i].getDescription()+" \n ";
		}
	}
	//itera pelos itens verificando se algum não tem algum texto
	var hasInvalidItem = false;
	for ( var i = 0; i < rows.length; i++) {
		var item  = rows[i];
		if(item.getValue() == ""){
			item.htmlElement.onchange = new Function("changeInvalidComponent(\""+item.getId()+"\",\"rows\");");
			item.setInvalid(true);
			hasInvalidItem = true;
		}
	}
	if(hasInvalidItem == true){
		message += " \n ";
		message += " - Há itens de verificação sem texto \n";
	}
	
	
	if(hasInvalidItem == true || hasInvalidMainFields == true){
		alert(message);
		return false;
	}

	return true;
}

function clearStepForm() {
	getById("step-description").value = "";
	getById("step-component").selectedIndex = 0;
	getById("step-combo-values").value = "";
	getById("combo-values").style.display = "none";
}

function addStep() {
	var addStepForm = getById("step-form");
	addStepForm.style.display = "inline";
}

/* validateStepForm(){
	var msg = "Os seguintes campos devem ser preenchidos: \n";
	
	var addStepForm = getById("step-form");
	var description = getById("step-description");
	var component = getById("step-component");
	var values = getById("step-combo-values");
	
	
	if(descripiton.value == ""){
		msg += "	- Descrição \n";
	}
	
	if(descripiton.value == ""){
		msg += "	- Descrição \n";
	}
	if(descripiton.value == ""){
		msg += "	- Descrição \n";
	}
	if(descripiton.value == ""){
		msg += "	- Descrição \n";
	}

} */

function saveStep() {
	
	var table = getById("$result_table");
	
	var addStepForm = getById("step-form");

	var description = getById("step-description");
	var component = getById("step-component");
	var values = getById("step-combo-values");

	var data = {
		"descr" : description.value,
		"component" : component.value,
		"values" : values.value
	};

	columns.push(data);

	var tdHeader = createEl("td");
	tdHeader.className = "header-cell";
	
	table.firstChild.appendChild(tdHeader);
	
	tdHeader.innerHTML = description.value;
	
	for ( var r = 0; r < rows.length; r++) {
		var td = createEl("td");
		td.className = "data-cell";
		table.childNodes[r+1].appendChild(td);
		var colId = "$" + r + "$" + columns.length;
		td.id = colId;
		var c = buildComponent(component.value, colId, values.value);
		c.render();
	}
	
	clearStepForm();
	addStepForm.style.display = "none";
}

function deleteItem(){
	var table = getById("$result_table");
			
	var node  = table.childNodes[table.childNodes.length - 1];
	table.removeChild(node);
	rows.pop();
}

function deleteStep(){
	var table = getById("$result_table");
	
	
	
	for ( var i = 0; i < table.childNodes.length; i++) {
		var tr = table.childNodes[i];
		var td  = tr.childNodes[tr.childNodes.length - 1];
		tr.removeChild(td);
	}
	
	columns.pop();
}

function cancelStep() {
	var addStepForm = getById("step-form");
	clearStepForm();
	addStepForm.style.display = "none";
}

function handleComponentCombo(combo) {
	var tdValues = getById("combo-values");
	if (combo.value == "ComboBox") {
		tdValues.style.display = "";
	} else {
		tdValues.style.display = "none";
	}
}

/**
 * Cria uma tag HTML
 * @param tagName
 * @returns
 */
function createEl(tagName) {
	return window.document.createElement(tagName);
}

function buildComponent(comp, colId, options){
	var component;
	
	//transforma uma string em um array de op��es do combo
	if (options.indexOf(";") > 0){
		options = options.split(";");
	}
	
	switch (comp) {
	case "EditBox":
		component = new EditBox(idCount++, colId);
		break;
	case "CheckBox":
		component = new CheckBox(idCount++, colId);
		break;
	case "ComboBox":
		component = new ComboBox(idCount++, colId);
		
		for ( var i = 0; i < options.length; i++) {
			component.addOption(options[i]);
		}
		break;
	case "TextArea":
		component = new TextArea(idCount++, colId);
		break;
	default:
		break;
	}
	
	return component;
}

function addItemList() {
	rowCount++;

	var table = getById("$result_table");

	if (table.childNodes.length == 0) {
		var trHeader = createEl("tr");
		table.appendChild(trHeader);
		var tdHeader = createEl("td");
		tdHeader.className = "header-cell";
		trHeader.appendChild(tdHeader);
		tdHeader.innerHTML = "Itens de verificação";
	}

	var tr = createEl("tr");
	table.appendChild(tr);
	var td = createEl("td");
	td.className = "header-cell";
	td.id = idCount++;
	tr.appendChild(td);
	var textArea = new TextArea(idCount++, td.id);
	textArea.render();
	// adiciona os TDs refrentes �s colunas
	rows.push(textArea);
	for ( var i = 0; i < columns.length; i++) {
		var colId = "$" + rowCount + "$" + i;
		var col = createEl("td");
		col.className = "data-cell";
		tr.appendChild(col);
		col.id = colId;
		var data = columns[i];
		var component = buildComponent(data.component, colId,data.values);
		component.render();
	}
}


function saveCheckList(){
	
	if(validate() == false){
		return;
	}
	
	var conn = new ClientConnector();
	conn.setCallBack(function(code){
		eval(code);
	});
	conn.send(buildCheckListData());
}

function buildCheckListData(){
	
	var edName = getById("name");
	var edModerator = getById("moderator");
	var taDescription = getById("description");
	var taArtifactAuthors = getById("artifactauthors");
	var edReviser = getById("reviser");
	
	var xmlData = "<?xml version=\"1.0\"?>";
	xmlData += "<ROOT>";
	xmlData += "<FORM value=\"$create_list_form\"> </FORM>";
	xmlData += "<ACTION value=\"INSERT\"> </ACTION>";
	xmlData += "<COMPONENT>";
	xmlData += "<DATA id=\"name\" value=\""+edName.value+"\" > </DATA>";
	xmlData += "</COMPONENT>";
	xmlData += "<COMPONENT>";
	xmlData += "<DATA id=\"moderator\" value=\""+edModerator.value+"\" > </DATA>";
	xmlData += "</COMPONENT>";
	xmlData += "<COMPONENT>";
	xmlData += "<DATA id=\"description\" value=\""+taDescription.value+"\" > </DATA>";
	xmlData += "</COMPONENT>";
	xmlData += "<COMPONENT>";
	xmlData += "<DATA id=\"artifactauthors\" value=\""+taArtifactAuthors.value+"\" > </DATA>";
	xmlData += "</COMPONENT>";
	xmlData += "<COMPONENT>";
	xmlData += "<DATA id=\"reviser\" value=\""+edReviser.value+"\" > </DATA>";
	xmlData += "</COMPONENT>";
	xmlData += "<ITEMS>";
	
	//adiciona os itens de verifica��o � lista 
	for ( var i = 0; i < rows.length; i++) {
		var row = rows[i];
		xmlData += "<ITEM value=\""+row.htmlElement.value+"\"></ITEM>";
	}
	
	xmlData += "</ITEMS>";
	
	xmlData += "<STEPS>";
	//adiciona os passos de verifica��o da lista ao xml
	for ( var i = 0; i < columns.length; i++) {
		
		var col = columns[i];
		xmlData += "<STEP description=\""+col.descr+"\" component=\""+col.component+"\" values=\""+col.values+"\" ></STEP>";
	}
	
	xmlData += "</STEPS>";
	
	xmlData += "</ROOT>";
	
	return xmlData;
}

function showSearchForm(){
	var searchForm = getById("search-form");
	searchForm.style.display = "inline";
}

function getUsers(){
	var xmlData = "<?xml version=\"1.0\"?>";
	
	xmlData += "<ROOT>";
	xmlData += "<FORM value=\""+FORM+"\"> </FORM>";
	xmlData += "<ACTION value=\"INITIALIZE\"></ACTION>";
	xmlData += "</ROOT>";
    var conn = new ClientConnector();
	
	conn.setCallBack(function(code){
		eval(code);
	});
	
	conn.send(xmlData);

}

function getCheckList(){
	
	columns = new Array();
	rows = new Array();
	
	rowCount = 0;
	
	formArea = getById("$form_area");
	
	var searchForm = getById("search-form");
		
	var editName = getById("search-form-edit");
	
	searchForm.style.display = "none";
	
	var xmlData = "<?xml version=\"1.0\"?>";
	
	xmlData += "<ROOT>";
	xmlData += "<FORM value=\"$create_list_form\"> </FORM>";
	xmlData += "<ACTION value=\"SELECT\"></ACTION>";
	xmlData += "<CHECK_LIST_NAME value=\""+editName.value+"\"></CHECK_LIST_NAME>";
	xmlData += "</ROOT>";
	
    var conn = new ClientConnector();
	
	conn.setCallBack(function(code){
		eval(code);
	});
	
	conn.send(xmlData);
}

function initialize(){
	
	//adiciona os campos de informação do checkList no array que vai validar eles quando gravar;
	
	compID = new EditBox("ID", "$ID");
	compID.setDescription("ID");
	
	compname = new EditBox("name", "$name");
	compname.setDescription("Nome");
	mainComponents.push(compname);
	
	compmoderator = new EditBox("moderator", "$moderator");
	compmoderator.setDescription("Moderador");
	mainComponents.push(compmoderator);
	
	compdescription = new TextArea("description", "$description");
	compdescription.setDescription("Descrição");
	mainComponents.push(compdescription);
	
	compartifactauthors = new TextArea("artifactauthors", "$artifactauthors");
	compartifactauthors.setDescription("Autores dos Artefatos");
	mainComponents.push(compartifactauthors);

	compreviser = new EditBox("reviser", "$reviser");
	compreviser.setDescription("Revisor");
	mainComponents.push(compreviser);
	
	compID.render();
	compname.render();
	compmoderator.render();
	compdescription.render();
	compartifactauthors.render();
	compreviser.render();
	
	compmoderator.setClassName("create-list-form-main-fields");
	compname.setClassName("create-list-form-main-fields");
	compID.setClassName("create-list-form-main-fields");
	compdescription.setClassName("create-list-form-main-fields");
	compartifactauthors.setClassName("create-list-form-main-fields");
	compreviser.setClassName("create-list-form-main-fields");
	
	
	
	getUsers();
}